import 'dart:async';
import 'dart:convert';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/base/base_refresh_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/goods_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/order_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/pay_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/userinfo_dao.dart';
import 'package:flutter_taotaoshipin/model/drama_main_info_entity.dart';
import 'package:flutter_taotaoshipin/model/goods_list_entity.dart';
import 'package:flutter_taotaoshipin/model/pay_config_list_entity.dart';
import 'package:flutter_taotaoshipin/pages/purchase/apple_iap_info.dart';
import 'package:flutter_taotaoshipin/pages/purchase/purchase_type.dart';
import 'package:flutter_taotaoshipin/pages/purchase/view/confirm_open_dialog.dart';
import 'package:flutter_taotaoshipin/util/apple_pay_utils.dart';
import 'package:flutter_taotaoshipin/util/events.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_taotaoshipin/value/sp_key.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher_string.dart';

import 'subscription_state.dart';

class SubscriptionController extends BaseRefreshController
    with GetSingleTickerProviderStateMixin {
  SubscriptionController({this.mainInfoEntity, this.showNavBack = true});

  final SubscriptionState state = SubscriptionState();

  // 显示返回
  bool showNavBack;

  // 主剧信息
  DramaMainInfoEntity? mainInfoEntity;

  // app生命周期
  late AppLifecycleListener _appLifecycleListener;

  /// 是否已经打开充值页面
  bool _hasOpenPayPage = false;

  /// 订单号
  String _orderId = '';

  /// 订单结果查询次数
  final int _maxCount = 3;
  int _currentCount = 1;

  // 支付结果监听
  StreamSubscription? _subscription;

  @override
  void onInit() {
    super.onInit();

    // 监听app生命周期
    _appLifecycleListener = AppLifecycleListener(
      onResume: () {
        // 查询订单状态
        if (_hasOpenPayPage) {
          _hasOpenPayPage = false;
          _loadOrderQueryData(_orderId);
        }
      },
    );

    // 监听苹果支付结果
    _subscription = eventBus.on<ApplePayResult>().listen((event) {
      if (event.status == 'success') {
        // 更新
        UserinfoDao.updateCenter();
        updateHasSubscripted();
      }
    });

    // 只受后台控制
    state.isAgreePrivacy = GlobalConfig.defaultSelVip_ios == 1 ? true : false;

    // 主剧信息
    if (mainInfoEntity == null) {
      if (Get.arguments is Map) {
        var entity = Get.arguments['mainInfoEntity'];
        mainInfoEntity = entity;
      }
    }
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    _subscription?.cancel();
    _appLifecycleListener.dispose();
    super.onClose();
  }

  @override
  fetchData({bool showLoading = true}) async {
    // 开始加载
    if (showLoading) {
      loadStatus = 0;
      update();
    }

    try {
      // 加载充值套餐列表
      await _loadGoodsListData();
      // 加载充值方式
      await _loadPayConfigListData();

      if (showLoading) {
        loadStatus = state.goodsList.isNotEmpty ? 1 : 2;
      }
    } catch (e) {
      if (showLoading) {
        loadStatus = 3;
      } else {
        EasyLoading.showError('加载失败');
      }
    }
    update();
    // 结束下拉
    refreshController.refreshCompleted(resetFooterState: true);
  }

  /// 充值套餐列表
  Future<void> _loadGoodsListData() async {
    try {
      var result = await GoodsDao.list();
      if (result.code == 0) {
        if (result.data != null) {
          state.goodsList = result.data!;

          // 置顶商品
          if (state.goodsList.isNotEmpty) {
            if (GlobalConfig.pinnerSubIndex > state.goodsList.length) {
              state.pinnedGood = state.goodsList.first;
            } else if (GlobalConfig.pinnerSubIndex > 0) {
              state.pinnedGood =
                  state.goodsList[GlobalConfig.pinnerSubIndex - 1];
            }
          }

          // 添加单剧买断
          if (mainInfoEntity?.canBuyoutDrama == 1) {
            var goods = GoodsListEntity()
              ..id = 1968
              ..goodsType = 1000
              ..amount = mainInfoEntity?.buyoutDramaAmount
              ..config = GoodsListConfig()
                  .copyWith(appleGoodsId: mainInfoEntity?.buyoutDramaId)
              ..name = '畅享全剧'
              ..bottomText = '单剧畅享';
            state.goodsList.insert(0, goods);
          }
          // 当前商品
          state.currGood = state.goodsList.first;
        } else {
          EasyLoading.showToast('获取充值套餐列表失败');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {
      EasyLoading.showToast('获取充值套餐列表失败');
    }
  }

  /// 充值模板列表
  Future<void> _loadPayConfigListData() async {
    try {
      var result = await PayDao.configList();
      if (result.code == 0) {
        if (result.data != null) {
          state.payConfigListEntity = result.data!;
          state.currPayConfig = result.data!.list!.first;

          state.isSubscripted = state.payConfigListEntity!.userSubTimes! > 0;
          update(['selected_item', 'isSubscripted']);
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {
      EasyLoading.showToast('获取充值模版失败');
    }
  }

  /// 创建订单
  Future<void> _loadOrderCreateData(
    PayConfigListList payConfig,
    GoodsListEntity goodsListEntity,
  ) async {
    try {
      EasyLoading.show(status: '正在下单');
      var result = await OrderDao.create(
        goodsListEntity.amount!,
        goodsListEntity.id!,
        payConfig.code!,
        payConfig.account!,
        dramaAction: mainInfoEntity?.id ?? 1,
        payPlatform: payConfig.platform,
      );
      if (result.code == 0) {
        if (result.data != null) {
          EasyLoading.dismiss();
          _orderId = result.data!.orderId!;
          // 数据不为空
          if (payConfig.code == 'apple_pay') {
            var jsonString = Uri.decodeFull(result.data!.payStr!);
            Map<String, dynamic> map = jsonDecode(jsonString);
            var uuid = map['uuid'];
            // 更新全局参数
            var payInfo = InAppPurchaseInfo(
              amount: goodsListEntity.amount,
              orderId: _orderId,
              productId: goodsListEntity.config?.appleGoodsId,
              uuid: uuid,
              payCode: payConfig.code,
            );
            AppController appController = Get.find();
            appController.updateApplePayInfo(payInfo);
            // 发起苹果支付
            await applePayUtils.startApplePay(
                goodsListEntity.config!.appleGoodsId!, uuid);
          } else if (payConfig.code == 'zfb_pay') {
            var url = Uri.decodeFull(result.data!.payStr!);
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          } else if (payConfig.code == 'zfb_app_pay') {
            var url = Uri.decodeFull(result.data!.payStr!);
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          } else {
            // var redirectUrl = Uri.encodeFull(
            // 'https://ts.933you.com/h5/#/pages/rechange/index?order_id=${result.data!.orderId}');
            var redirectUrl = Uri.encodeFull(Constant.urlScheme);
            var url =
                '${result.data!.payReferer}?to_url=${result.data!.payStr}&redirect_url=$redirectUrl';
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          }
        } else {
          EasyLoading.showError('下单失败');
        }
      } else {
        EasyLoading.showError(result.message);
      }
    } catch (e) {
      EasyLoading.showError('网络错误');
    }
  }

  /// 订单状态主动查询
  Future<void> _loadOrderQueryData(String orderId, {bool retry = true}) async {
    try {
      EasyLoading.show(status: '订单查询中');
      var result = await OrderDao.query(orderId);
      if (result.code == 0) {
        if (result.data != null) {
          if (result.data!.status == 1) {
            EasyLoading.showSuccess('充值成功');
            // 充值成功，加载用户中心
            await UserinfoDao.updateCenter();
          } else {
            // 充值失败，重试3次
            if (retry) {
              _currentCount++;
              if (_currentCount > _maxCount) {
                _currentCount = 1;
                EasyLoading.showError('充值失败');
                return;
              } else {
                // 延迟1.5秒查询下一次
                Future.delayed(const Duration(milliseconds: 1500), () {
                  _loadOrderQueryData(orderId);
                });
              }
            } else {
              EasyLoading.showError('充值失败');
            }
          }
        } else {
          EasyLoading.showError('数据为空');
        }
      } else {
        EasyLoading.showError(result.message);
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
  }

  void agreePrivacyBtnClicked() {
    state.isAgreePrivacy = !state.isAgreePrivacy;
    update(['privacy_agreement']);
    // 保存状态
    SpUtil.putBool(SpKey.hasMonthTips, true);
  }

  void itemClicked(GoodsListEntity entity) {
    state.currGood = entity;
    update(['selected_item']);
  }

  void showPrivateTips({bool isPinned = false}) {
    Get.dialog(ConfirmOpenDialog(
      onSuccess: () {
        agreePrivacyBtnClicked();
        toPay(isPinned: isPinned);
      },
    ));
  }

  toPay({bool isPinned = false}) {
    if (state.currPayConfig != null) {
      // 置顶商品
      if (isPinned) {
        _loadOrderCreateData(state.currPayConfig!, state.pinnedGood!);
      } else {
        _loadOrderCreateData(state.currPayConfig!, state.currGood!);
      }
    } else {
      EasyLoading.showToast("当前支付方式不支持");
    }
  }

  // 支付按钮
  void payButtonClicked({bool isPinned = false}) {
    if (!state.isAgreePrivacy) {
      showPrivateTips(isPinned: isPinned);
      return;
    }
    toPay(isPinned: isPinned);
  }

  // 更新已订阅
  void updateHasSubscripted() {
    state.isSubscripted = true;
    update(['selected_item', 'isSubscripted']);
  }
}
